import {
  IOS_PERMISSIONS_ENUM,
  AuthCodeEnum,
  AuthEnum,
  PERMISSION_ID_ENUM,
} from "../enums";
import { queryPermissionNamesByPermissionId } from "../tools";
import { IAuthResponse } from "../types";

/**  判断推送权限是否开启 */
export const judgeIosPermissionPush = (): boolean => {
  let result = false;
  const UIApplication = plus.ios.import("UIApplication");
  const app = UIApplication.sharedApplication();
  let enabledTypes = 0;
  if (app.currentUserNotificationSettings) {
    const settings = app.currentUserNotificationSettings();
    enabledTypes = settings.plusGetAttribute("types");
    console.log(`enabledTypes1:${enabledTypes}`);
    // eslint-disable-next-line eqeqeq
    if (enabledTypes == 0) {
      console.log("推送权限没有开启");
    } else {
      result = true;
      console.log("已经开启推送功能!");
    }
    plus.ios.deleteObject(settings);
  } else {
    enabledTypes = app.enabledRemoteNotificationTypes();
    // eslint-disable-next-line eqeqeq
    if (enabledTypes == 0) {
      console.log("推送权限没有开启!");
    } else {
      result = true;
      console.log("已经开启推送功能!");
    }
    console.log(`enabledTypes2:${enabledTypes}`);
  }
  plus.ios.deleteObject(app);
  plus.ios.deleteObject(UIApplication);
  return result;
};

/**  判断定位权限是否开启 */
export const judgeIosPermissionLocation = (): boolean => {
  let result = false;
  const cllocationManger = plus.ios.import("CLLocationManager");
  const status = cllocationManger.authorizationStatus();
  const enable = cllocationManger.locationServicesEnabled();

  // eslint-disable-next-line eqeqeq
  result = status != 2 && status != 0;
  console.log(`定位权限开启：${result} - ${enable}`);
  // 以下代码判断了手机设备的定位是否关闭，推荐另行使用方法 checkSystemEnableLocation
  /* const enable = cllocationManger.locationServicesEnabled();
	  const status = cllocationManger.authorizationStatus();
	  console.log("enable:" + enable);
	  console.log("status:" + status);
	  if (enable && status != 2) {
		  result = true;
		  console.log("手机定位服务已开启且已授予定位权限");
	  } else {
		  console.log("手机系统的定位没有打开或未给予定位权限");
	  } */
  plus.ios.deleteObject(cllocationManger);
  return result;
};

/**  判断麦克风权限是否开启 */
export const judgeIosPermissionRecord = (): boolean => {
  let result = false;
  const avaudiosession = plus.ios.import("AVAudioSession");
  const avaudio = avaudiosession.sharedInstance();
  const permissionStatus = avaudio.recordPermission();
  console.log(`permissionStatus:${permissionStatus}`);
  // eslint-disable-next-line eqeqeq
  if (permissionStatus == 1684369017 || permissionStatus == 1970168948) {
    console.log("麦克风权限没有开启");
  } else {
    result = true;
    console.log("麦克风权限已经开启");
  }
  plus.ios.deleteObject(avaudiosession);
  return result;
};

/**  判断相机权限是否开启 */
export const judgeIosPermissionCamera = (): boolean => {
  let result = false;
  const AVCaptureDevice = plus.ios.import("AVCaptureDevice");
  const authStatus = AVCaptureDevice.authorizationStatusForMediaType("vide");
  console.log(`authStatus:${authStatus}`);
  // eslint-disable-next-line eqeqeq
  if (authStatus == 3) {
    result = true;
    console.log("相机权限已经开启");
  } else {
    console.log("相机权限没有开启");
  }
  plus.ios.deleteObject(AVCaptureDevice);
  return result;
};

/**  判断相册权限是否开启 */
export const judgeIosPermissionPhotoLibrary = (): boolean => {
  let result = false;
  const PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
  const authStatus = PHPhotoLibrary.authorizationStatus();
  console.log(`authStatus:${authStatus}`);
  // eslint-disable-next-line eqeqeq
  if (authStatus == 3) {
    result = true;
    console.log("相册权限已经开启");
  } else {
    console.log("相册权限没有开启");
  }
  plus.ios.deleteObject(PHPhotoLibrary);
  return result;
};

/**  判断通讯录权限是否开启 */
export const judgeIosPermissionContact = (): boolean => {
  let result = false;
  const CNContactStore = plus.ios.import("CNContactStore");
  const cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
  // eslint-disable-next-line eqeqeq
  if (cnAuthStatus == 3) {
    result = true;
    console.log("通讯录权限已经开启");
  } else {
    console.log("通讯录权限没有开启");
  }
  plus.ios.deleteObject(CNContactStore);
  return result;
};

/**  判断日历权限是否开启 */
export const judgeIosPermissionCalendar = (): boolean => {
  let result = false;
  const EKEventStore = plus.ios.import("EKEventStore");
  const ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
  // eslint-disable-next-line eqeqeq
  if (ekAuthStatus == 3) {
    result = true;
    console.log("日历权限已经开启");
  } else {
    console.log("日历权限没有开启");
  }
  plus.ios.deleteObject(EKEventStore);
  return result;
};

/**  判断备忘录权限是否开启 */
export const judgeIosPermissionMemo = (): boolean => {
  let result = false;
  const EKEventStore = plus.ios.import("EKEventStore");
  const ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
  // eslint-disable-next-line eqeqeq
  if (ekAuthStatus == 3) {
    result = true;
    console.log("备忘录权限已经开启");
  } else {
    console.log("备忘录权限没有开启");
  }
  plus.ios.deleteObject(EKEventStore);
  return result;
};

/** 检查IOS系统的设备服务GPS是否开启 */
export const checkIOS_GPS_Service = () => {
  let result = false;
  const cllocationManger = plus.ios.import("CLLocationManager");
  result = cllocationManger.locationServicesEnabled();
  console.log(`系统定位开启:${result}`);
  plus.ios.deleteObject(cllocationManger);
  return result;
};

/**  判断通话权限是否开启
 * @remark ios不需要判断拨打电话权限，此处直接返回true是为了兼容模块规范
 */
export const judgeIosPermissionCallPhone = () => {
  return true;
};
/**
 * iOS权限查询
 * @param permission 权限名称
 * @returns {IAuthResponse}
 */
export const checkIOSPermissions = (
  permission: IOS_PERMISSIONS_ENUM
): IAuthResponse => {
  const permissionMap = {
    [IOS_PERMISSIONS_ENUM.LOCATION]: judgeIosPermissionLocation,
    [IOS_PERMISSIONS_ENUM.CAMERA]: judgeIosPermissionCamera,
    [IOS_PERMISSIONS_ENUM.PHOTO_LIBRARY]: judgeIosPermissionPhotoLibrary,
    [IOS_PERMISSIONS_ENUM.PUSH]: judgeIosPermissionPush,
    [IOS_PERMISSIONS_ENUM.CALL_PHONE]: judgeIosPermissionCallPhone,
    [IOS_PERMISSIONS_ENUM.CONTACT]: judgeIosPermissionContact,
    [IOS_PERMISSIONS_ENUM.RECORD]: judgeIosPermissionRecord,
    [IOS_PERMISSIONS_ENUM.CALENDAR]: judgeIosPermissionCalendar,
    [IOS_PERMISSIONS_ENUM.MEMO]: judgeIosPermissionMemo,
    [IOS_PERMISSIONS_ENUM.GPS]: checkIOS_GPS_Service,
  };
  const defaultFn = () => null;
  const targetFn = permissionMap[permission] || defaultFn;
  const res = targetFn();
  return {
    code: res ? AuthCodeEnum.AUTHORIZED : AuthCodeEnum.DENIED,
    message: `permission is ${res ? AuthEnum.AUTHORIZED : AuthEnum.DENIED}`,
    data: res,
  };
};

const iosRequestPermissionMap = {
  [IOS_PERMISSIONS_ENUM.LOCATION]: "LOCATION",
  [IOS_PERMISSIONS_ENUM.CAMERA]: "CAMERA",
  [IOS_PERMISSIONS_ENUM.PHOTO_LIBRARY]: "WRITE",
  [IOS_PERMISSIONS_ENUM.PUSH]: "NOTIFICATION",
  [IOS_PERMISSIONS_ENUM.CALL_PHONE]: "CALL_PHONE",
  [IOS_PERMISSIONS_ENUM.CONTACT]: "READ_CONTACTS",
  [IOS_PERMISSIONS_ENUM.RECORD]: "AUDIO",
  [IOS_PERMISSIONS_ENUM.CALENDAR]: "CALENDAR",
  [IOS_PERMISSIONS_ENUM.MEMO]: "REMINDER",
};

const requestIOSPermission = (
  permissionId: IOS_PERMISSIONS_ENUM
): Promise<IAuthResponse> =>
  new Promise((resolve) => {
    const targetPermission = iosRequestPermissionMap[permissionId];
    console.log(`请求权限：4${targetPermission}`);
    if (permissionId === IOS_PERMISSIONS_ENUM.CALL_PHONE) {
      resolve({
        code: AuthCodeEnum.AUTHORIZED,
        data: true,
        message: "iOS不需要判断拨打电话权限，可以直接调用",
      });
      return;
    }
    if (permissionId === IOS_PERMISSIONS_ENUM.LOCATION) {
      uni.getLocation({
        success: () => {
          console.error("权限调用成功");
          resolve({
            code: AuthCodeEnum.AUTHORIZED,
            data: true,
            message: "权限调用成功",
          });
        },
        fail: () => {
          console.error("权限调用失败");
          resolve({
            code: AuthCodeEnum.DENIED,
            data: false,
            message: "权限调用失败",
          });
        },
      });
      return;
    }
    const permissionObj = uni.requireNativePlugin("LuanQing-Permission");
    permissionObj.requestPermission(
      { permission: targetPermission },
      (res) => {
        console.error("权限申请成功嘞", res);
        resolve({
          code: AuthCodeEnum.AUTHORIZED,
          data: true,
          message: "权限申请成功",
        });
      },
      (res) => {
        console.error("权限申请失败嘞", res);
        resolve({
          code: AuthCodeEnum.DENIED,
          data: false,
          message: "权限申请失败",
        });
      }
    );
  });

export const invokeIOSSystemAuthorizationPopupByPermissionId = async (
  permissionId: PERMISSION_ID_ENUM
): Promise<IAuthResponse> => {
  const permissionName = queryPermissionNamesByPermissionId({
    permission: permissionId,
    platform: "ios",
  }) as IOS_PERMISSIONS_ENUM;
  if (!iosRequestPermissionMap?.[permissionName]) {
    return Promise.resolve({
      code: AuthCodeEnum.UNSUPPORTED,
      data: false,
      message: `unsupported permission ${permissionName}`,
    });
  }
  const res = await requestIOSPermission(permissionName);
  return Promise.resolve(res);
};

/**
 * 调用iOS系统权限弹窗
 * @param permissionId 权限名称
 * @returns {Promise<IAuthResponse>}
 */
export const invokeIOSSystemAuthorizationPopup = async (
  permission: PERMISSION_ID_ENUM | string | Array<PERMISSION_ID_ENUM | string>
): Promise<IAuthResponse> => {
  if (Array.isArray(permission)) {
    const execList = await Promise.all(
      permission.map((p) =>
        invokeIOSSystemAuthorizationPopupByPermissionId(p as PERMISSION_ID_ENUM)
      )
    );
    const pass = execList.every(
      (item) => item.code === AuthCodeEnum.AUTHORIZED
    );
    return {
      code: pass ? AuthCodeEnum.AUTHORIZED : AuthCodeEnum.DENIED,
      data: pass,
      message: `${
        pass
          ? ""
          : `unsupported permission ${execList
              .map((item) => item.message)
              .join(",")}`
      }`,
    };
  }
  return invokeIOSSystemAuthorizationPopupByPermissionId(
    permission as PERMISSION_ID_ENUM
  );
};
